package com.ikproducts.manualian.client.entrypoint;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.ikproducts.manualian.client.ContentData;
import com.ikproducts.manualian.client.ContentType;
import com.ikproducts.manualian.client.ContentWidget;
import com.ikproducts.manualian.client.GreetingService;
import com.ikproducts.manualian.client.GreetingServiceAsync;
import com.ikproducts.manualian.client.IContentWidget;
import com.ikproducts.manualian.client.library.CategoryManager;

public class SimpleManual implements EntryPoint {

	private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);

	private final String ADDBUTTON_LABEL = "LABEL_ADDBUTTON";
//	private final String CATEGORY_SELECT_MESSAGE_FORMAT = "カテゴリ%sを選択してください...";
	private final String CATEGORY_SELECT_MESSAGE_FORMAT = "カテゴリを選択してください...";
	
	// コンテンツ種別選択ダイアログ
	private DialogBox typeSelectDlg = null;
	
	// コンテンツグリッド
	private List<ContentData> contentsList = null;

	private int current = 0;
	
	ClickHandler addButtonClickHandler = null;

	List<IContentWidget> contents = null;

	private String userName = "";
	
	List<ListBox> _CategoryInputBox = new ArrayList<ListBox>();

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		typeSelectDlg = new DialogBox();
		contents = new ArrayList<IContentWidget>();
		contentsList = new ArrayList<ContentData>();
		
		CategoryManager categoryManager = CategoryManager.getInstance();
		List<String> l = categoryManager.getTopCategories();
		ListBox listBox = new ListBox();
//		listBox.addItem(String.format(CATEGORY_SELECT_MESSAGE_FORMAT, String.valueOf(1)));
		listBox.addItem(CATEGORY_SELECT_MESSAGE_FORMAT);
		for(String s : l){
			listBox.addItem(s);
		}
		listBox.addChangeHandler(new CategoryChangeHandler(0));
		VerticalPanel vp = new VerticalPanel();
		vp.add(listBox);
		_CategoryInputBox.add(listBox);
		RootPanel.get("category_select").add(vp);
		
		
		// TEMPボタンを追加
		VerticalPanel vpTemp = new VerticalPanel();
		for(int i=0; i<10; i++){
			Button b = new Button("BUTTON_" + i);
			b.setTitle("" + i);
			b.addClickHandler(new TempButtonClickHandler());
			vpTemp.add(b);
		}		
		RootPanel.get("temp_button").add(vpTemp);
		
		
		//-------------------------------------------------------------
		// ログイン・ログアウトの判定
		//-------------------------------------------------------------
		final StringBuilder strHtml = new StringBuilder();
		greetingService.greetServer("", new AsyncCallback<Map<String,String>>(){
			public void onFailure(Throwable caught) {
			}

			public void onSuccess(Map<String,String> result) {
				if(result.get("isLoggedIn").equals("true")){
					String email = result.get("emailAddress");
					strHtml.append("<b>" + email + "</b>");
					strHtml.append("&nbsp;&nbsp;");
					strHtml.append("<a href=\"news/\">マイページ </a>&nbsp;&nbsp;<a href=\"" 
							+ result.get("logoutUrl")
							+ "\">ログアウト</a>");
					int sepIdx = email.indexOf("@");
					if(sepIdx != -1){
						userName = email.substring(0, sepIdx);
					}
					else{
						userName = email;
					}
				}else{
					// ここへはこないはず
				}
				HTML html = new HTML();
				html.setHTML(strHtml.toString());
				RootPanel.get("sub_header").add(html);
			}
		});

		//-----------------------------------------------------
		// 記事コンテンツ種別ボタンのクリックハンドラ郡
		//-----------------------------------------------------
		ClickHandler contentTypeHandler = new ClickHandler(){
			public void onClick(ClickEvent event){
				Image imgButton = (Image)event.getSource();
				String btnTitle = imgButton.getTitle();
				
				if(btnTitle.equals("html")){
					contents.add(current, new ContentWidget(ContentType.CONTENT_TYPE_HTML, "html"));
				}
				else if(btnTitle.equals("image")){
					contents.add(current, new ContentWidget(ContentType.CONTENT_TYPE_IMAGE, "image"));
				}
				else if(btnTitle.equals("code")){
					contents.add(current, new ContentWidget(ContentType.CONTENT_TYPE_COED, "code"));
				}
				else if(btnTitle.equals("headline")){
					contents.add(current, new ContentWidget(ContentType.CONTENT_TYPE_HEADLINE, "headline"));
				}
				else if(btnTitle.equals("pageend")){
					contents.add(current, new ContentWidget(ContentType.CONTENT_TYPE_PAGEEND, "pageend"));
				}
				contents.add(current, getAddImageButton());
				typeSelectDlg.hide();
				updateContents();
			}
		};
		// 追加ボタンのクリックハンドラ
		addButtonClickHandler = new ClickHandler(){
			public void onClick(ClickEvent event){
				ImageWidhIndexInfo imgButton = (ImageWidhIndexInfo)event.getSource();
				current = imgButton.getIndex();
				typeSelectDlg.center();
			}
		};
		
		// ダイアログのキャンセルボタンのクリックハンドラ
		ClickHandler dlgCancelClickHandler = new ClickHandler(){
			public void onClick(ClickEvent event){
				typeSelectDlg.hide();
			}
		};
				
		// 登録ボタンのクリックハンドラ
		ClickHandler registerButtonClickHandler = new ClickHandler(){
			public void onClick(ClickEvent evt){
 				contentsList.clear();
				for(IContentWidget w : contents){
					if(w.getContentType() != ContentType.CONTENT_TYPE_ADDBUTTON){
						contentsList.add(new ContentData(w.getContentType(), w.getContent()));
					}
				}
				if(contentsList.size() == 0){
					Window.alert("記事データがありません。");
					return;
				}
		
				
				String categoryPathOfDisplayName = makeCategoryPath();
				List<String> decisions = getCategoryDecisions();
				int categoryID = CategoryManager.getInstance().getCategoryID(decisions);
				String categoryPathOfIDName = CategoryManager.getInstance().getCategoryIDName(decisions);
				
				greetingService.saveArticle(contentsList, userName, "Javaとは何ぞや", categoryPathOfDisplayName, categoryPathOfIDName, categoryID, new AsyncCallback<String>(){
					public void onFailure(Throwable caught) {
						Window.alert(caught.getMessage());
					}
		
					public void onSuccess(String result) {
						Window.alert(result);
					}
				});
			}
		};
		
		HorizontalPanel contentTypePanel = new HorizontalPanel();
		
		// コンテンツ種別選択ボタンを作成
		Image imgHeadLine = new Image("/images/article_content_type_headline.JPG");
		Image imgHtml = new Image("/images/article_content_type_html.JPG");
		Image imgImage = new Image("/images/article_content_type_image.JPG");
		Image imgCode = new Image("/images/article_content_type_code.jpg");
		Image imgPageEnd = new Image("/images/article_content_type_pageend.JPG");
		imgHeadLine.setTitle("headline");
		imgHtml.setTitle("html");
		imgImage.setTitle("image");
		imgCode.setTitle("code");
		imgPageEnd.setTitle("pageend");

		// 各ボタンにハンドラを設定
		imgHeadLine.addClickHandler(contentTypeHandler);
		imgHtml.addClickHandler(contentTypeHandler);
		imgImage.addClickHandler(contentTypeHandler);
		imgCode.addClickHandler(contentTypeHandler);
		imgPageEnd.addClickHandler(contentTypeHandler);

		// ダイアログの閉じるボタン
		Button dlgCancelButton = new Button("キャンセル");
		dlgCancelButton.addClickHandler(dlgCancelClickHandler);
				
		// パネルに追加 
		contentTypePanel.add(imgHeadLine);
		contentTypePanel.add(imgHtml);
		contentTypePanel.add(imgImage);
		contentTypePanel.add(imgCode);
		contentTypePanel.add(imgPageEnd);
		contentTypePanel.add(dlgCancelButton);
		
		// ダイアログを作る
		typeSelectDlg.setAnimationEnabled(true);
		typeSelectDlg.setText("コンテンツタイプ選択");
		typeSelectDlg.setWidget(contentTypePanel);
		
		// 追加ボタンを作成
		contents.add(getAddImageButton());
		
		
		updateContents();
		
		
		VerticalPanel vertPanel = new VerticalPanel();
		TextBox titleTB = new TextBox();
		vertPanel.add(new Label("タイトル"));
		vertPanel.add(titleTB);
		RootPanel.get("article_title").add(vertPanel);
	
		Button entryButton = new Button("登録");
		entryButton.addClickHandler(registerButtonClickHandler);
		RootPanel.get("register").add(entryButton);
	}
	

	private void updateContents(){
		VerticalPanel vertPanel = new VerticalPanel();
		int cnt = 0;
		for(IContentWidget w : contents){
			if(w.getContentType() == ContentType.CONTENT_TYPE_ADDBUTTON){
				((ImageWidhIndexInfo)w).setIndex(cnt);
			}
			vertPanel.add((Widget)w);
			cnt++;
		}
		RootPanel.get("contents").clear();
		RootPanel.get("contents").add(vertPanel);
	}
	
	private ImageWidhIndexInfo getAddImageButton(){
		ImageWidhIndexInfo img = new ImageWidhIndexInfo();
		img.setUrl("/images/article_content_add.JPG");
		img.setTitle(ADDBUTTON_LABEL);
		img.addClickHandler(addButtonClickHandler);
		return img;
	}
	
	private class ImageWidhIndexInfo extends Image implements IContentWidget{
		int index;
		String label;
		
		public ImageWidhIndexInfo(){
			index = 0;
			label = "";
		}
		
		public void setIndex(int index){
			this.index = index;
		}
		public int getIndex(){
			return this.index;
		}

		@Override
		public String getContent() {
			return null;
		}

		@Override
		public int getContentType() {
			return ContentType.CONTENT_TYPE_ADDBUTTON;
		}
	}

	//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_
	//
	//	イベントハンドラ
	//
	//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_
	
	/**
	 * カテゴリ選択のListBoxが変更されたときのハンドラクラス
	 * @author i.kisanuki
	 *
	 */
	class CategoryChangeHandler implements ChangeHandler{
	
		private int _CategoryId;
		
		public CategoryChangeHandler(int categoryId){
			_CategoryId = categoryId;
		}
		@Override
		public void onChange(ChangeEvent event) {
			ListBox target = (ListBox)event.getSource();
			
			// 先頭のインデックスには「選択してください」がはいっているので
			// それが選択されたときには何もしない
			int listBoxLength = _CategoryInputBox.size();
			for(int i=_CategoryId+1; i<listBoxLength; i++){
				_CategoryInputBox.remove(_CategoryId+1);
			}
			List<String> decisions = new ArrayList<String>();
			for(int i=0; i<=_CategoryId; i++){
				int selectedIndex = _CategoryInputBox.get(i).getSelectedIndex();
				decisions.add(_CategoryInputBox.get(i).getItemText(selectedIndex));
			}
			// カテゴリを取得
			List<String> textListAdd = new ArrayList<String>();
			CategoryManager.getInstance().getCategories(decisions, textListAdd);

			// リストボックスに入れてリストに追加
			ListBox listBox = new ListBox();
			if(textListAdd.size() > 0){
//				listBox.addItem(String.format(CATEGORY_SELECT_MESSAGE_FORMAT, _CategoryId + 1));
				listBox.addItem(CATEGORY_SELECT_MESSAGE_FORMAT);
				for(String s : textListAdd){
					listBox.addItem(s);
				}
				listBox.addChangeHandler(new CategoryChangeHandler(_CategoryId+1));
				_CategoryInputBox.add(listBox);
			}
			
			// ページを更新
			RootPanel.get("category_select").clear();
			VerticalPanel vp = new VerticalPanel(); 
			for(ListBox l : _CategoryInputBox){
				vp.add(l);
			}
			RootPanel.get("category_select").add(vp);
		} 
	}

	class TempButtonClickHandler implements ClickHandler{

		@Override
		public void onClick(ClickEvent event) {
			Button b = (Button)event.getSource();
			
			String s = b.getTitle();
			if(s.equals("0")){
				greetingService.GetTemp(new AsyncCallback<String>(){
					public void onFailure(Throwable caught) {
						Window.alert(caught.getMessage());
					}
		
					public void onSuccess(String result) {
						Window.alert(result);
					}
				});
			}else if(s.equals("1")){
				Window.alert("bbb");
				
			}
			
		}
		
	}
	
	//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_
	//
	//	内部ユーティリティ
	//
	//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_
	
	private String makeCategoryPath(){
		StringBuilder path = new StringBuilder();
		for(ListBox ctrl : _CategoryInputBox){
			int index = ctrl.getSelectedIndex();
			if(ctrl.getSelectedIndex() == 0){
				break;
			}
			if(path.toString().length() != 0){
				path.append(CategoryManager.PathSeparator);
			}
			path.append(ctrl.getItemText(index));
		}		
		return path.toString();
	}
	
	private List<String> getCategoryDecisions(){
		List<String> list = new ArrayList<String>();
		for(ListBox ctrl : _CategoryInputBox){
			int index = ctrl.getSelectedIndex();
			if(ctrl.getSelectedIndex() == 0){
				break;
			}
			list.add(ctrl.getItemText(index));
		}		
		return list;
	}

}
